package xyz.kongbai121.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.omg.CORBA.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.kongbai121.demo.domain.UserWeb;
import xyz.kongbai121.demo.mapper.UserWebMapper;
import xyz.kongbai121.demo.service.IUserWebService;
import xyz.kongbai121.demo.util.UserPowerException;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserWebServiceImpl implements IUserWebService {
    @Autowired
    private UserWebMapper userWebMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String loginByWeb(String username,String password) {
        UserWeb user = userWebMapper.getUser(username, password);
        if (user == null || user.getOpenid() == null) throw new UserPowerException("请先登录");
        String token = UUID.randomUUID().toString().replaceAll("-","");
        //TODO 生成令牌并返回给用户
        redisTemplate.opsForValue().set(token,user.getOpenid(),30, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public String registerByWeb(String token, String username, String password) {
        String openid = redisTemplate.opsForValue().get(token);
        int row = userWebMapper.insert(new UserWeb(openid, username, password));
        if (row > 0){
            return "绑定成功";
        }else {
            return "绑定失败";
        }
    }

    @Override
    public String updateByWeb(String token, String username, String password) {
        String openid = redisTemplate.opsForValue().get(token);
        UpdateWrapper<UserWeb> wrapper = new UpdateWrapper<>();
        wrapper.eq("openid",openid);
        wrapper.eq("username",username);
        wrapper.set("password",password);
        int row = userWebMapper.update(null, wrapper);
        if (row > 0){
            return "修改成功";
        }else {
            return "修改出错";
        }
    }

    @Override
    public String getUsername(String token) {
        if (token == null || !redisTemplate.hasKey(token)) throw new UserPowerException("请先登录");
        String openid = redisTemplate.opsForValue().get(token);
        String username = userWebMapper.getUsername(openid);
        return username;
    }
}
